const http = require('http');
const url = require('url');
const fs = require('fs');
const util = require('util');

const httpDir = process.argv[2];
const httpPort = process.argv[3];
const IP = "172.16.242.226"
const mimetype = {
	'txt': 'text/plain',
	'htm': 'text/html',
	'html': 'text/html',
	'css': 'text/css',
	'xml': 'application/xml',
	'json': 'application/json',
	'js': 'application/javascript',
	'jpg': 'image/jpeg',
	'jpeg': 'image/jpeg',
	'gif': 'image/gif',
	'png': 'image/png',
	'svg': 'image/svg+xml'
}
const defaultPage = [
	'index.html'
]

const TIP = `
 _ __  ___  ___ _ ____   _____ _ __ 
| '_ \\/ __|/ _ \\ '__\\ \\ / / _ \\ '__|
| | | \\__ \\  __/ |   \\ V /  __/ |   
|_| |_|___/\\___|_|    \\_/ \\___|_|   
                                    
Server running at ${IP}:${httpPort}/
`
console.log(TIP);

const page_404 = function(req, res, path){
	res.writeHead(404, {
	  'Content-Type': 'text/html'
	});
	res.write('<!doctype html>\n');
	res.write('<title>404 Not Found</title>\n');
	res.write('<h1>Not Found</h1>');
	res.write(
	'<p>The requested URL ' +
	 path + 
	' was not found on this server.</p>'
	);
	res.end();
}

const page_500 = function(req, res, error){
	res.writeHead(500, {
	  'Content-Type': 'text/html'
	});
	res.write('<!doctype html>\n');
	res.write('<title>Internal Server Error</title>\n');
	res.write('<h1>Internal Server Error</h1>');
	res.write('<pre>' + util.inspect(error) + '</pre>');
}


http.createServer(function (req, res) {
	let urlSet  = url.parse(req.url);
	let pathname = urlSet.pathname.indexOf('.') != -1 ? urlSet.pathname :  urlSet.pathname + defaultPage[0];
	let realPath = httpDir + pathname;
	console.log((new Date()) + " : " + realPath);
	fs.exists(realPath, function(exists){
		if(!exists){
			return page_404(req, res, pathname);
		} else {
			let file = fs.createReadStream(realPath);
			res.writeHead(200, {
				 'Content-Type': mimetype[realPath.split('.').pop()] || 'text/plain'
			});
			file.on('data', res.write.bind(res));
			file.on('close', res.end.bind(res));      
			file.on('error', function(err){
				return page_500(req, res, err);
			});
		}    
	});  
}).listen(httpPort, IP);